package com.quanxiaoha.weblog.common.service.impl;

import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
import lombok.extern.slf4j.Slf4j;
import okhttp3.*;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.util.EntityUtils;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import java.io.IOException;
import java.nio.charset.StandardCharsets;

@Service
@Slf4j
public class DeepSeekService {

    @Value("${deepseek.api-key}")
    private String apiKey;
    @Value("${deepseek.api-url}")
    private String apiUrl;

    public String askDeepSeek(String question) throws Exception {


        // 构造Prompt提示词，要求返回结构化数据
        String prompt = String.format(
                "作为思维导图生成器，请以JSON格式返回以下主题的思维导图结构。格式示例：" +
                        "{ \\\"root\\\": { \\\"topic\\\": \\\"主题\\\", \\\"children\\\": " +
                        "[ { \\\"topic\\\": \\\"分支1\\\", \\\"children\\\": [...] }, " +
                        "{ \\\"topic\\\": \\\"分支2\\\" } ] } }" +
                        "主题：%s", question
        );

        try (CloseableHttpClient httpClient = HttpClients.createDefault()) {
            HttpPost httpPost = new HttpPost(apiUrl);
            httpPost.setHeader("Authorization", "Bearer " + apiKey);
            httpPost.setHeader("Content-Type", "application/json");

            String jsonBody = String.format(
                    "{\"model\": \"deepseek-chat\", \"messages\": [{\"role\": \"user\", \"content\": \"%s\"}]}",
                    prompt
            );
            log.info("<UNK>{}", jsonBody);

            httpPost.setEntity(new StringEntity(jsonBody));
            log.info("<OK>{}", httpPost);
            try (CloseableHttpResponse response = httpClient.execute(httpPost)) {
                log.info("<OK>{}", response);
                return EntityUtils.toString(response.getEntity());
            }
        }
    }

    public String generateMindMapData(String topic) throws IOException {

        // 构造Prompt提示词，要求返回结构化数据
        String prompt = String.format(
                                "作为思维导图生成器，请以JSON格式返回以下主题的思维导图结构。格式示例：" +
                                "{ \\\"root\\\": { \\\"topic\\\": \\\"主题\\\", \\\"children\\\": " +
                                "[ { \\\"topic\\\": \\\"分支1\\\", \\\"children\\\": [...] }, " +
                                "{ \\\"topic\\\": \\\"分支2\\\" } ] } }" +
                                "主题：%s", topic
        );

        // 调用DeepSeek API（同步请求）
        OkHttpClient client = new OkHttpClient();
        String jsonBody = String.format(
                "{\"model\": \"deepseek-chat\", \"messages\": [{\"role\": \"user\", \"content\": \"%s\"}]}",
                prompt
        );
        log.info("<UNK>{}", jsonBody);
        byte[] bytes = jsonBody.getBytes(StandardCharsets.UTF_8);
        RequestBody requestBody = RequestBody.create(bytes, MediaType.get("application/json"));
        Request request = new Request.Builder()
            .url(apiUrl)
            .addHeader("Authorization", "Bearer " + apiKey)
            .post(requestBody)
            .build();

        try (Response response = client.newCall(request).execute()) {
        if (!response.isSuccessful()) throw new IOException("API调用失败");
        return parseResponse(response.body().string()); // 提取返回的JSON文本

        }
    }

    private String parseResponse(String jsonResponse) throws JsonProcessingException {
        JsonNode rootNode = new ObjectMapper().readTree(jsonResponse);
        return rootNode.path("choices").get(0).path("message").path("content").asText();
    }

}
